



class LinkNode:
    def __init__(self, data) -> None:
        self.data = data
        self.next = None
        
class LinkList:
    def __init__(self, lst, reverse=False) -> None:
        if len(lst) <= 0:
            raise ValueError
        self.head = LinkNode(None)
        self.head.next = LinkNode(lst[0])
        pre_node = self.head.next
        for i in lst[1:]:
            link_node = LinkNode(i)
            pre_node.next = link_node
            pre_node = link_node
        self.index = self.head
        if reverse:
            self.reverse()
        
    def reverse(self):
        if self.length() <= 1:
            return False
        pre_index = self.head.next
        index = pre_index.next
        pre_index.next = None
        while True:
            post_index = index.next
            index.next = pre_index
            if not post_index:
                break
            pre_index = index
            index = post_index
            post_index = index.next
        self.head.next = index
        self.index = self.head
        
    def length(self):
        length = 0
        index = self.head.next
        while index:
            index = index.next
            length += 1
        return length
            
    def __iter__(self):
        return self
    
    def __next__(self):
        self.index = self.index.next
        if self.index:
            return self.index.data
        else:
            self.index = self.head
            raise StopIteration


link_list = LinkList([2,3,4,5,'hh',9])

for i in link_list:
    print(i, end='\t')
print('length:', link_list.length())

for i in link_list:
    print(i, end='\t')
print()

for i in LinkList([2,3,4,5,'hh',9], reverse=True):
    print(i, end='\t')
print()

link_list.reverse()
for i in link_list:
    print(i, end='\t')
print()

for i in LinkList([2], reverse=True):
    print(i, end='\t')
print()


